<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>观察一个元素是否在可视窗口内（intersection Observer）</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .main {
            position: relative;
            width: 200px;
            height: 200px;
            background-color: red;
        }

        .sub {
            position: absolute;
            top: 0;
            left: 0;
            width: 10px;
            height: 10px;
            border-radius: 10px;
            background-color: blue;
            transition: transform 0.2s ease;
            /*will-change: transform;*/
        }
    </style>
</head>
<body>
<div class="main">
    <span class="sub"></span>
</div>
<script>
    // 交叉观察器 API（Intersection Observer API）提供了一种异步检测目标元素与祖先元素或顶级文档的视口相交情况变化的方法。
    const subDom = document.querySelector(".sub");
    const mainDom = document.querySelector(".main");
    const intersectionObserver = new IntersectionObserver((entries) => {
        console.log(entries);
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const ratio = entry.intersectionRatio;
                if (ratio > 0.5) {
                    subDom.style.backgroundColor = 'green'; // 完全在可视区域内
                } else {
                    subDom.style.backgroundColor = 'yellow'; // 部分在可视区域内
                }
            } else {
                subDom.style.backgroundColor = 'blue'; // 不在可视区域内
            }
        });
    }, {
        root: mainDom,
        rootMargin: "5px 5px", // 扩展根元素的边界和设置margin一样
        threshold: [0, 0.5, 1] // 设置多个阈值
    });
    intersectionObserver.observe(subDom);
    // 开始监听
    document.addEventListener('mousemove', function(event) {
        const innerWidth = event.view.innerWidth;
        const innerHeight = event.view.innerHeight;
        let mouseX = 0;
        let mouseY = 0;
        if(event.clientX < 0 || event.clientX === 0) {
            mouseX = 0;
        } else if(event.clientX > innerWidth - 5) {
            mouseX = innerWidth - 10;
        } else {
            mouseX = event.clientX - 5;
        }
        if(event.clientY < 0 || event.clientY === 0) {
            mouseY = 0;
        } else if(event.clientY > innerHeight - 5) {
            mouseY = innerHeight - 10;
        } else {
            mouseY = event.clientY - 5;
        }
        requestAnimationFrame(function() {
            subDom.style.transform = `translate(${mouseX}px, ${mouseY}px)`;
        })
    });
</script>
</body>
</html>
